package lumis.portal.webfilereplication;

import java.io.File;
import java.util.Collection;

import lumis.portal.filesystem.PortalFile;

import org.apache.commons.io.FileUtils;

/**
 * File replicator that interacts with a target repository in the local 
 * file system.
 * 
 * @version $Revision: 13093 $ $Date: 2011-05-28 18:40:18 -0300 (Sat, 28 May 2011) $
 * @since 6.0.0
 */
public class LocalFileReplicator extends AbstractFileReplicator
{
	/**
	 * The local repository root.
	 * @since 6.0.0
	 */
	private File repositoryRoot;

	public void initialize() throws FileReplicationException
	{
		// clear properties
		repositoryRoot = null;
		
		// read properties
		Collection<WebFileReplicationPropertyValue> values = getWebFileReplication().getPropertyValues();
		for (WebFileReplicationPropertyValue customPropertyValue : values)
		{
			String name = customPropertyValue.getProperty().getName();
			if ("Path".equals(name))
			{
				String value = null;
				if (customPropertyValue.getValue() != null && customPropertyValue.getValue().trim().length() > 0)
				{
					value = customPropertyValue.getValue();
				}
				else
				{
					// no value
					continue;
				}
			
				repositoryRoot = new File(value);
				break;
			}
		}
		
		// check properties
		if (repositoryRoot == null)
			throw new FileReplicationException("Value for 'Path' property not found in " + getWebFileReplication().getName() + ".");
	}

	public void write(PortalFile file) throws FileReplicationException
	{
		File destinationFile = getFileInRepository(file);
		if (file.isDirectory())
		{
			if (!destinationFile.mkdirs())
				if (!destinationFile.exists())
					throw new FileReplicationException("Could not create directory at '" + destinationFile.getAbsolutePath() + "'");
		}
		else
		{
			try
			{
				FileUtils.copyFile(file, destinationFile);
			}
			catch (Exception e)
			{
				throw new FileReplicationException(e);
			}
		}
	}

	public void delete(PortalFile file) throws FileReplicationException
	{
		File destinationFile = getFileInRepository(file);
		if (!destinationFile.delete())
			if (destinationFile.exists())
				throw new FileReplicationException("Could not delete file '" + destinationFile.getAbsolutePath() + "'");
	}

	/**
	 * Returns the relative path of a file in the repository.
	 * 
	 * @param file
	 *            The file used to generate the path.
	 * @return the relative path of a file in the repository.
	 * @since 6.0.0
	 */
	private File getFileInRepository(PortalFile file)
	{
		return new File(repositoryRoot, file.getPortalFilePath().getRelativePath());
	}
}
